
#include "arrow.h"
#include "resourcemanager.h"
#include "gamemanager.h"
#include "unit.h"
#include "gameplayscene.h"

#define __super         Bullet

static const float POWDER_POT_BULLET_SPEED = 600.0f;

ArrowBullet::ArrowBullet(const Point& from, const Point& to)
{
	src = from;
	dst = to;
	position = src;

	type = BulletType::piercing;
}

ArrowBullet::~ArrowBullet() {
}

void ArrowBullet::init() {
	__super::init();

	sprite = CREATE_SPRITE("textures/fx/arrow.png");
	_halfArrowLengh = sprite->getContentSize().width / 2.0f;

	float t = 0.6f;
	float velocity_x = (dst.x - src.x) / t;
	float fall_range = 0.5f * GRAVITY * t * t;
	float velocity_y = (dst.y - src.y - fall_range) / t;

	speed = Point(velocity_x, velocity_y);

	sprite->setPosition(SCALE_PT(src));
	sprite->setRotation(static_cast<float>(-speed.getAngle() * 180.0f / M_PI));
}

bool ArrowBullet::update(float ticks) {
	bool isArrivedTarget = false;

	Point realStep = speed * ticks;
	speed.y += GRAVITY * ticks;

	Point newPos = position + realStep;

	if(speed.y <= 0) {
		Point offset = realStep.normalize() * _halfArrowLengh;
		Point arrowHead = newPos + offset;
		float distance = dst.getDistance(arrowHead);

		if(distance < _halfArrowLengh) {
			isArrivedTarget = true;

			if(target) {
				Point targetPoint = target->sprite->getBonePositionRelativeToWorld("head");
				float dist = targetPoint.getDistance(dst);
				isHitTarget = (dist <= 15.0f);
			}
		} else if(arrowHead.y < dst.y) {
			isArrivedTarget = true;
		}
	}

	position = newPos;

	sprite->setPosition(SCALE_PT(position));
	sprite->setRotation(static_cast<float>(-speed.getAngle() * 180.0f / M_PI));

	if(isArrivedTarget) {
		if(!target || !target->isAlive() || !isHitTarget){
			Sprite* spr = CREATE_SPRITE("textures/fx/arrow_decal.png");
			spr->setPosition(SCALE_PT(dst));
			spr->setRotation(-speed.getAngle() * 180.0f / M_PI);
			
			GM->getGamePlayScene()->addSceneNode(spr);
			GM->getGamePlayScene()->removeNodeWithFadeInOut(spr, 0, 2, 1);
		} else {
			// play hit sound
		}
	}

	return !isArrivedTarget;
}
